package com.portal.sso.core.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.portal.sso.core.config.SsoConfig;

public class PortalSecureUtil {
    /**
     * 解密字符串
     *
     * @param msg
     * @return
     */
    public static String AesDecode(String msg, String pwd_key) {
        byte[] key = null;
        if (StrUtil.isEmpty(pwd_key)) {
            key = SsoConfig.SSO_REQUEST_PWD_KEY.getBytes();

        } else {
            key = pwd_key.getBytes();

        }
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

// 解密为字符串
        String decryptStr = aes.decryptStr(msg);
        return decryptStr;
    }

    public static String AesEncode(String msg, String pwd_key) {
        byte[] key = null;
        if (StrUtil.isEmpty(pwd_key)) {
            key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();//SsoConfig.SSO_REQUEST_PWD_KEY.getBytes();

        } else {
            key = pwd_key.getBytes();

        }
       // AES aes = new AES(Mode.ECB, Padding.PKCS5Padding,key);
       SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        byte[] decrypt = aes.encrypt(msg);
        String encode = Base64.encode(decrypt);
//        String decryptStr = aes.decryptStr(decrypt, CharsetUtil.CHARSET_UTF_8);
        return encode;
    }

    public static String GetBase64Key() {
        byte[] sale = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        String encode = Base64.encode(sale);
        return encode;

    }
    public static String GetHex16Key() {
        byte[] sale = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        String encode = HexUtil.encodeHexStr(sale);
        return encode;

    }

    public static void main(String[] args) {
        String content = "testdss时代的ddd中文";
//       for (int i =0;i<100;i++){


        String key = GetBase64Key();
        String key2 = GetHex16Key();

        System.out.println(key);
        System.out.println(key2);

        String enstr = AesEncode(content, key);
        String destr = AesDecode(enstr, key);
        System.out.println(enstr);
        System.out.println(destr);

        String enstr2 = AesEncode(content, key2);
        String destr2 = AesDecode(enstr2, key2);
        System.out.println(enstr2);
        System.out.println(destr2);
//       }
    }
}
